package com.applink.sell_proof.fragment;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.DetailClaim;
import com.applink.sell_proof.R;
import com.applink.sell_proof.SearchOpportunity;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.database.table.DistributorDBHelper;
import com.applink.sell_proof.model.Claim;
import com.applink.sell_proof.model.Distributor;
import com.applink.sell_proof.util.Utility;

public class InvoiceBrieftFragment extends SherlockFragment implements
		OnClickListener, OnCheckedChangeListener, OnDateSetListener {

	private String TAG = "InvoiceBrieftFragment";

	private String mOpportunityID = "";

	private long mDistributorId = 0;

	private TextView txtDate;
	private TextView mOpportunityNameTextField;

	private ViewGroup mBrieftLayout;

	private ViewGroup mClaimTotalBlock;

	private ViewGroup mClaimDistributor;

	private Spinner mDistributorDropDownList;
	private String currentDateandTime;
	private SimpleDateFormat simpleDateFormat;
	private String textDate = "";
	private long currentCal ;		

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		currentDateandTime = simpleDateFormat.format(new Date());
		 currentCal = Calendar.getInstance().getTimeInMillis();		
		textDate = currentDateandTime;
		
		// Inflating layout
		mBrieftLayout = (ViewGroup) inflater.inflate(R.layout.invoice_brieft,
				null);

		addItemsOnDistributorList();

		mOpportunityNameTextField = (TextView) mBrieftLayout
				.findViewById(R.id.opportunity_name);
		mOpportunityNameTextField.setOnClickListener(this);

		final CompoundButton checkbox = ((CompoundButton) mBrieftLayout
				.findViewById(R.id.search_opportunity_lock));
		checkbox.setOnCheckedChangeListener(this);

		mClaimTotalBlock = (ViewGroup) mBrieftLayout
				.findViewById(R.id.claimtotalblock);

		mClaimDistributor = (ViewGroup) mBrieftLayout
				.findViewById(R.id.linear_distributor);
		//mBrieftLayout.findViewById(R.id.invoice_date).	
		txtDate = (TextView)mBrieftLayout.findViewById(R.id.invoice_date);
		txtDate.setText(currentDateandTime);
		mBrieftLayout.findViewById(R.id.invoice_date).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						Calendar date = Calendar.getInstance();

						DatePickerDialog dateDialog = new DatePickerDialog(
								getActivity(), InvoiceBrieftFragment.this, date
										.get(Calendar.YEAR), date
										.get(Calendar.MONTH), date
										.get(Calendar.DAY_OF_MONTH));

						dateDialog.setTitle(R.string.cus_invoice_date);

						dateDialog.show();
					}
				});
		
		setHasOptionsMenu(true);

		toggleOpportunityNameTextField(checkbox.isChecked());

		Log.i(TAG, "onCreateView is called");
		return mBrieftLayout;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.opportunity_name:
			Intent intent = new Intent(getActivity(), SearchOpportunity.class);
			getActivity().startActivityForResult(intent,
					SearchOpportunity.SEARCH_OPPORTUNITY);
			break;

		default:
			break;
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		toggleOpportunityNameTextField(isChecked);
	}

	private void toggleOpportunityNameTextField(boolean isChecked) {
		if (isChecked) {
			// Constant.CHECK_OPPORTUNITY = true;

			mOpportunityNameTextField.setClickable(true);
			mOpportunityNameTextField
					.setBackgroundResource(R.drawable.textfield_hoto_light);
			mClaimDistributor.setVisibility(View.GONE);
			mClaimTotalBlock.setVisibility(View.VISIBLE);

			mBrieftLayout.findViewById(R.id.claimcompnameblock).setVisibility(
					View.VISIBLE);

			((TextView) mBrieftLayout.findViewById(R.id.invoice_date_label))
					.setText(R.string.invoice_date);

			((TextView) mBrieftLayout.findViewById(R.id.invoice_no_label))
					.setText(R.string.invoice_no);

			if (mMenu != null) {
				MenuItem detail = mMenu.findItem(R.id.claim_detail);
				if (detail != null)
					detail.setVisible(false);
			}
		} else {
			// Constant.CHECK_OPPORTUNITY = false;

			mOpportunityNameTextField.setClickable(false);
			mOpportunityID = "";

			((TextView) mClaimTotalBlock.findViewById(R.id.claimtotalprice))
					.setText("0");
			mClaimDistributor.setVisibility(View.VISIBLE);
			mClaimTotalBlock.setVisibility(View.GONE);

			mBrieftLayout.findViewById(R.id.claimcompnameblock).setVisibility(
					View.GONE);

			((TextView) mBrieftLayout.findViewById(R.id.invoice_date_label))
					.setText(R.string.disty_invoice_date);

			((TextView) mBrieftLayout.findViewById(R.id.invoice_no_label))
					.setText(R.string.disty_invoice_no);

			if (mMenu != null) {
				MenuItem detail = mMenu.findItem(R.id.claim_detail);
				if (detail != null)
					detail.setVisible(true);
			}
		}
		// try {
		// getActivity().supportInvalidateOptionsMenu();
		// BaseClaim.instantBaseClaim.supportInvalidateOptionsMenu();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }

	}

	// add items into spinner dynamically
	private void addItemsOnDistributorList() {
		Log.i(TAG, "addItemsOnDistributorList : called");
		mDistributorDropDownList = (Spinner) mBrieftLayout
				.findViewById(R.id.distibutors);

		List<Distributor> dl = DistributorDBHelper.getAllDistributor();

		ArrayAdapter<Distributor> distributorAdapter = new DistributorAdapter(
				getActivity(), dl);

		mDistributorDropDownList.setAdapter(distributorAdapter);

		mDistributorDropDownList
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						mDistributorId = ((DistributorAdapter) mDistributorDropDownList
								.getAdapter()).getDistributorId(position);

						Log.i(TAG, "Distributor ID : " + mDistributorId
								+ " position : " + position);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});
	}

	public String getCustomerName() {
		return ((TextView) getView().findViewById(R.id.invoice_customer_name))
				.getText().toString();
	}

	public String getInvoiceNo() {
		return ((TextView) getView().findViewById(R.id.invoice_no)).getText()
				.toString();
	}

	public Claim getClaimHeader() {
		Claim claim = new Claim();

		claim.setId(mClaimId);
		String customername = ((TextView) getView().findViewById(
				R.id.invoice_customer_name)).getText().toString();
		System.out.println(">>>>>customer name = " + customername);
		String invoiceNo = ((TextView) getView().findViewById(R.id.invoice_no))
				.getText().toString();

		String type = (!mOpportunityID.equals("")) ? Claim.TYPE_PROJECT
				: Claim.TYPE_UNIT;

		claim.setOpportunityId(mOpportunityID);
		claim.setOpportunityName(mOpportunityNameTextField.getText().toString());

		claim.setCustomerCompanyName(customername);
		claim.setInvoiceNo(invoiceNo);
		if(mDate == 0){
			mDate = currentCal;
		}
		claim.setDate(mDate);
		claim.setType(type);
		claim.setDistributorId(mDistributorId);

		if (!mOpportunityID.equals("")) {
			double total = Double.parseDouble(((TextView) getView()
					.findViewById(R.id.claimtotalprice)).getText().toString());
			claim.setTotal(total);
		}

		return claim;
	}

	Menu mMenu;

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		Log.w(DetailClaim.TAG, "Fra_onCreateOptionsMenu");
		inflater.inflate(R.menu.claim_menu, menu);

		mMenu = menu;
		super.onCreateOptionsMenu(menu, inflater);
	}

	private long mDate;

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {		
		GregorianCalendar closeDate = new GregorianCalendar(year, monthOfYear,
				dayOfMonth);
		mDate = closeDate.getTimeInMillis();		

		if(mDate > currentCal){
			Toast.makeText(getActivity(), "Date must be today or no earlier than 90 days.", 5000).show();
			textDate = currentDateandTime;
		}else if(mDate < currentCal ){
			int x = Integer.parseInt(String.valueOf((currentCal - mDate)/(1000  * 24 * 60 * 60)));
			if(x > 90){
				Toast.makeText(getActivity(), "Date must be today or no earlier than 90 days.", 5000).show();
				textDate = currentDateandTime;
			}else{
				textDate = DateFormat.getDateFormat(getActivity()).format(mDate);
			}
		}else{
			textDate = DateFormat.getDateFormat(getActivity()).format(mDate);
		}
		((TextView) getView().findViewById(R.id.invoice_date))
				.setText(textDate);
	}

	public void setOpportunityId(String id, String name) {
		mOpportunityID = id;
		mOpportunityNameTextField.setText(name);
	}

	private long mClaimId = 0;

	public void setClaimHeader(Claim claim) {

		((TextView) getView().findViewById(R.id.invoice_customer_name))
				.setText(claim.getCustomerCompanyName());
		((TextView) getView().findViewById(R.id.invoice_customer_name)).setVisibility(View.GONE);
		((TextView) getView().findViewById(R.id.invoice_no)).setText(claim
				.getInvoiceNo());

		String opportunityName = claim.getOpportunityName();
		String claimtype = claim.getType();
		if (claimtype.equals(Claim.TYPE_PROJECT)) {
			Constant.checkBox = true;
			((CheckBox) getView().findViewById(R.id.search_opportunity_lock))
					.setChecked(true);
			((TextView) getView().findViewById(R.id.opportunity_name))
					.setText(opportunityName);

			((TextView) getView().findViewById(R.id.claimtotalprice))
					.setText(Double.toString(claim.getTotal()));
		}

		mDate = claim.getDate();
		String textDate = DateFormat.getDateFormat(getActivity()).format(mDate);
		((TextView) getView().findViewById(R.id.invoice_date))
				.setText(textDate);

		mClaimId = claim.getId();

		Log.i(TAG, "setClaimHeader is Called");
		mDistributorDropDownList
				.setSelection(((DistributorAdapter) mDistributorDropDownList
						.getAdapter()).getPosition(claim.getDistributorId()));
	}

	public void disableEdit() {
		Utility.disableTextView(InputType.TYPE_NULL, (ViewGroup) mBrieftLayout);
	}

	class DistributorAdapter extends ArrayAdapter<Distributor> {

		private List<Distributor> mDistributors;

		public DistributorAdapter(Context context, List<Distributor> objects) {
			super(context, android.R.layout.simple_spinner_item, objects);
			mDistributors = objects;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.i(TAG, "DistributorAdapter:" + "getView");
			return initView(position, convertView);
		}

		@Override
		public View getDropDownView(int position, View convertView,
				ViewGroup parent) {
			Log.i(TAG, "DistributorAdapter:" + "getDropDownView");
			return initView(position, convertView);
		}

		private View initView(int position, View convertView) {

			if (convertView == null)
				convertView = View.inflate(getContext(),
						android.R.layout.simple_spinner_dropdown_item, null);

			convertView.setBackgroundColor(getResources().getColor(
					android.R.color.white));

			TextView tvText1 = (TextView) convertView
					.findViewById(android.R.id.text1);

			tvText1.setTextColor(getResources().getColor(android.R.color.black));
			tvText1.setText(getItem(position).getName());

			Log.i(TAG, "DistributorAdapter:" + "initView");
			return convertView;
		}

		public int getPosition(long distributorId) {

			for (Distributor d1 : mDistributors) {
				if (d1.getId() == distributorId) {
					return mDistributors.indexOf(d1);
				}
			}

			return -1;
		}

		public long getDistributorId(int position) {
			return mDistributors.get(position).getId();
		}
	}
}
